<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>GitHub 仓库批量删除</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            max-width: 800px;
            margin: 20px auto;
            padding: 0 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #24292e;
            margin-bottom: 20px;
        }
        .input-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #24292e;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .repo-list {
            margin: 20px 0;
            max-height: 400px;
            overflow-y: auto;
        }
        .repo-item {
            padding: 10px;
            border: 1px solid #ddd;
            margin-bottom: 5px;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .repo-item:hover {
            background-color: #f6f8fa;
        }
        .repo-info {
            flex-grow: 1;
        }
        .checkbox {
            margin-right: 10px;
        }
        button {
            background-color: #2ea44f;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background-color: #2c974b;
        }
        button.delete {
            background-color: #d73a49;
        }
        button.delete:hover {
            background-color: #cb2431;
        }
        .loading {
            text-align: center;
            padding: 20px;
            display: none;
        }
        .error {
            color: #d73a49;
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #d73a49;
            border-radius: 4px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>GitHub 仓库批量删除</h1>
        
        <div class="input-group">
            <label for="token">GitHub 个人访问令牌:</label>
            <input type="text" id="token" placeholder="请输入你的 GitHub Token">
        </div>

        <button id="fetchRepos">获取仓库列表</button>
        
        <div class="error" id="error"></div>
        <div class="loading" id="loading">正在加载...</div>
        
        <div class="repo-list" id="repoList"></div>
        
        <button class="delete" id="deleteSelected" style="display: none;">删除选中的仓库</button>
    </div>

    <script>
        let repoData = [];

        // 抽取获取仓库列表的函数
        async function fetchRepositories(token) {
            showLoading(true);
            try {
                // 添加时间戳参数避免缓存
                const timestamp = new Date().getTime();
                const response = await fetch(`https://api.github.com/user/repos?per_page=100&timestamp=${timestamp}`, {
                    headers: {
                        'Authorization': `token ${token}`,
                        'Accept': 'application/vnd.github.v3+json',
                        'Cache-Control': 'no-cache',
                        'Pragma': 'no-cache'
                    }
                });

                if (!response.ok) {
                    throw new Error('获取仓库列表失败');
                }

                repoData = await response.json();
                displayRepos(repoData);
                document.getElementById('deleteSelected').style.display = 'block';
            } catch (error) {
                showError(error.message);
                throw error;
            } finally {
                showLoading(false);
            }
        }

        document.getElementById('fetchRepos').addEventListener('click', async () => {
            const token = document.getElementById('token').value;
            if (!token) {
                showError('请输入 GitHub Token');
                return;
            }

            try {
                await fetchRepositories(token);
            } catch (error) {
                // 错误已在 fetchRepositories 中处理
            }
        });

        function displayRepos(repos) {
            const repoList = document.getElementById('repoList');
            repoList.innerHTML = '';

            repos.forEach(repo => {
                const repoItem = document.createElement('div');
                repoItem.className = 'repo-item';
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'checkbox';
                checkbox.dataset.repo = repo.full_name;

                const repoInfo = document.createElement('div');
                repoInfo.className = 'repo-info';
                repoInfo.innerHTML = `
                    <strong>${repo.full_name}</strong><br>
                    <small>
                        ${repo.private ? '私有' : '公开'} | 
                        语言: ${repo.language || '未知'} | 
                        最后更新: ${new Date(repo.updated_at).toLocaleString()}
                    </small>
                `;

                repoItem.appendChild(checkbox);
                repoItem.appendChild(repoInfo);
                repoList.appendChild(repoItem);
            });
        }

        document.getElementById('deleteSelected').addEventListener('click', async () => {
            const token = document.getElementById('token').value;
            const selectedRepos = Array.from(document.querySelectorAll('.checkbox:checked'))
                .map(checkbox => checkbox.dataset.repo);

            if (selectedRepos.length === 0) {
                showError('请选择要删除的仓库');
                return;
            }

            if (!confirm(`确认要删除以下 ${selectedRepos.length} 个仓库吗？\n${selectedRepos.join('\n')}`)) {
                return;
            }

            showLoading(true);
            let errors = [];

            for (const repo of selectedRepos) {
                try {
                    const response = await fetch(`https://api.github.com/repos/${repo}`, {
                        method: 'DELETE',
                        headers: {
                            'Authorization': `token ${token}`,
                            'Accept': 'application/vnd.github.v3+json'
                        }
                    });

                    if (!response.ok) {
                        errors.push(`删除 ${repo} 失败`);
                    }
                } catch (error) {
                    errors.push(`删除 ${repo} 时发生错误: ${error.message}`);
                }
            }

            // 等待一段时间确保删除操作在 GitHub 服务器上完全生效
            await new Promise(resolve => setTimeout(resolve, 2000));

            // 删除操作完成后，重新从 GitHub 获取最新的仓库列表
            try {
                await fetchRepositories(token);
            } catch (error) {
                errors.push('更新仓库列表失败');
            }
            
            if (errors.length > 0) {
                showError(errors.join('\n'));
            } else {
                alert('所选仓库已成功删除！');
            }
        });

        function showError(message) {
            const error = document.getElementById('error');
            error.textContent = message;
            error.style.display = 'block';
            setTimeout(() => {
                error.style.display = 'none';
            }, 5000);
        }

        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
        }
    </script>
</body>
</html>